package logic

import (
	"context"
	"encoding/hex"
	"errors"
	"math/rand"
	"time"
)

import (
	du "zxs-micro-2/zxs-micro-proto/demouser/user"
)

type user struct {
	account   string
	pwd       string
	token     string
	loginTime time.Time
}

var localMem = make(map[string]user)
var accountPwd = make(map[string]user)

func init() {
	rand.Seed(time.Now().Unix())
}

func GenerateRandomString(n int) string {
	result := make([]byte, n/2)
	rand.Read(result)
	return hex.EncodeToString(result)
}

func RegisterUserLogic(ctx context.Context, req *du.UserRegisterRequest) (rsp *du.UserRegisterResponse, err error) {
	rsp = new(du.UserRegisterResponse)
	if req.RegisterCode != "123456" {
		rsp.Types = "wrong code"
		return
	}
	if req.Pwd != req.VerifyPwd {
		rsp.Types = "different pwd"
		return
	}
	if req.Account == "" {
		rsp.Types = "empyt account"
		return
	}
	tkn := GenerateRandomString(16)
	u := user{
		account:   req.Account,
		pwd:       req.Pwd,
		token:     tkn,
		loginTime: time.Now(),
	}
	localMem[tkn] = u
	accountPwd[u.account] = u
	rsp.Types = tkn
	return rsp, err
}

func UserLoginLogic(ctx context.Context,
	request *du.UserLoginRequest) (rsp *du.UserLoginResponse, err error) {
	rsp = new(du.UserLoginResponse)
	acc := request.Account
	u, ok := accountPwd[acc]
	if !ok {
		err = errors.New("account not found!")
		return
	}
	if u.pwd != request.Pwd {
		err = errors.New("pwd wrong")
		return
	}
	if u.token == "" {
		u.token = GenerateRandomString(16)
	}
	rsp.Token = u.token
	return
}

func UserInfoLogic(ctx context.Context,
	request *du.UserInfoRequest) (info *du.UserInfoResponse, err error) {
	info = new(du.UserInfoResponse)
	tkn := request.Token
	u, ok := localMem[tkn]
	if ok {
		info.Account = u.account
		info.LoginTime = u.loginTime.String()
	}
	return
}
